package com.torry.edss.infras.util;

import cn.hutool.extra.pinyin.PinyinUtil;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

public class CompanyUtil {
    /**
     * 解析公司缩略词
     *
     * @param companyName 公司名称
     * @return String
     */
    public static String parseCompanyAcronym(String companyName) {
        companyName = companyName.toUpperCase();

        StringBuilder result = new StringBuilder();

        for (int i = 0; i < companyName.toCharArray().length; i++) {
            if (!PinyinUtil.isChinese(companyName.charAt(i))) {
                result.append(companyName.charAt(i));
            } else {
                int start = i;
                int segmentIndex = i;
                for (int j = i; j < companyName.toCharArray().length; j++) {
                    if (!PinyinUtil.isChinese(companyName.charAt(j))) {
                        segmentIndex = j;
                        i = j - 1;
                        break;
                    }
                    if (j == companyName.toCharArray().length - 1) {
                        i = j;
                    }
                    segmentIndex++;
                }
                String substring = companyName.substring(start, segmentIndex);
                HanyuPinyinOutputFormat hanyuPinyinOutputFormat = new HanyuPinyinOutputFormat();
                hanyuPinyinOutputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
                hanyuPinyinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
                try {
                    String s1 = PinyinHelper.toHanYuPinyinString(substring, hanyuPinyinOutputFormat, "", true);
                    StringBuilder szm = new StringBuilder();
                    int l = 0;
                    for (int k = 0; k < s1.toCharArray().length; k++) {
                        char c = s1.charAt(k);
                        if (Character.isDigit(c)) {
                            szm.append(s1.charAt(l));
                            l = k + 1;
                        }
                    }
                    result.append(szm);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return result.toString();
    }
}
